#!/usr/bin/python3
import sched
import threading
import time

from monitor.log_schedule_handler import loggers
from monitor.redis_pool import OPRedis

app_log = None

schedule = sched.scheduler(time.time, time.sleep)


def load_dcs_log_handler():
    global app_log
    app_log = loggers


def dcs_schedule():
    load_dcs_log_handler()
    t = threading.Thread(target=dcs_job)
    t.setDaemon(True)  # 设置为后台线程，这里默认是False，设置为True之后则主线程不用等待子线程.
    t.start()


def dcs_job():
    inc = 10.0
    schedule.enter(0, 0, update_cache, (inc,))
    schedule.run()


def update_cache(inc):
    app_log.info({"type": "update_start."})
    start_time = time.time()
    schedule_task()

    end_time = time.time()
    app_log.info({"type": "update_end.", "exec_time": end_time - start_time})
    schedule.enter(inc, 0, update_cache, (inc,))


def schedule_task(key, *args):
    app_log.info({"type": "wincc_task_start."})
    start_time = time.time()
    try:
        conn = OPRedis()
        conn.set_list_value(key, *args)
        conn.del_list_value(key, 0, 2)
        res = conn.get_list_value(key, 0, -1)
        print(res)

    except Exception as e:
        app_log.error({"type": "wincc_task", "msg": str(e)})
    finally:
        end_time = time.time()
        app_log.info({"type": "wincc_task_end.", "exec_time": end_time - start_time})
